const path = require('path');
const chalk = require('chalk');
const memFs = require('mem-fs');
const memFsEditor = require('mem-fs-editor');
const fse = require('fs-extra');
const shelljs = require('shelljs');
const figlet = require('figlet');

const log = console.log;
const error = console.error;

const initCommand = require('./command');
const initSetting = require('./setting');
const output = require('./output');

class Creator {

    constructor() {
        const store = memFs.create();
        this._mfs = memFsEditor.create(store);

        this._setting = {
            name: '',
            version: '1.0.0',
            description: '',
            author: ''
           
        };
        this._rootPath = path.resolve(__dirname, '..');
        this._tplPath = path.resolve(__dirname, '..', 'template');
    }

    do() {
        log(chalk.green(
            figlet.textSync("KID CLI")
        ));
        initCommand();
        log(chalk.white(`按以下步骤完成项目的构建.`));
        log('');
        // 获取配置
        initSetting().then(setting => {
            this._setting = Object.assign({}, this._setting, setting);

            log(chalk.cyanBright('the setting:'));
            log(this._setting);
            log('');

            // 输出文件
            output(this).then(res => {
                // 加入git版本管理
                /*shelljs.cd(setting.name);
                if (shelljs.exec('git init').code !== 0) {
                    shelljs.echo('Error: git init failed.');
                    shell.exit(1);
                };*/
                log(chalk.green(`Project construction completed！`));
                log(chalk.green(`Start project: cd ${setting.name} && npm install`));
            });
        });
    }
    getTplPath(file) {
        return path.join(this._tplPath, file);
    }
    copy(file, to) {
        const filePath = this.getTplPath(file);
        fse.copy(filePath, to).then(() => log('success!'))
            .catch(err => error(err));
    }
    copySync(file, to) {
        const filePath = this.getTplPath(file);
        try {
            fse.copySync(filePath, to);
            log('success!')
        } catch (err) {
            error(err)
        }
    }
    copyTpl(file, to, data = {}) {
        const filePath = this.getTplPath(file);
        if (this._mfs.exists(filePath)) this._mfs.copyTpl(filePath, to, data);
        else
            error(filePath + '不存在')
    }

}

module.exports = Creator;